import axios from "axios"
import { Message } from "element-ui"
import store from "@/store"
import { getToken } from "@/utils/auth"


const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 50000
})

service.interceptors.request.use(
  config => {
    config.headers["token"] = getToken()
    
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    
    if (res.code !== 20000 && res.code !== 200) {
      if (response.status === 401 || res.code === 20001) {
        store.dispatch("user/resetToken").then(() => {
          location.reload()
        })
      }
      return Promise.reject(service.interceptors.response)
    }
    else {
      return res.data
    }
  },
  error => {
    if (error.message.includes("timeout")) {
      Message({
        message: "网络超时",
        type: "error",
        duration: 5 * 1000
      })
    }
    else if (error.message === "Network Error") {
      Message({
        message: "网络连接错误",
        type: "error",
        duration: 5 * 1000
      })
    }
    else {
      if (error.response.data) {
        Message({
          message: error.response.statusText,
          type: "error",
          duration: 5 * 1000
        })
      }
      else {
        Message({
          message: "接口路径找不到",
          type: "error",
          duration: 5 * 1000
        })
      }
    }
    
    return Promise.reject(error)
  }
)

export default service
